package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1 判断当前是否是登录请求，如果是登录则放行

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取url
        String reqUrl = request.getURI().getPath();
        if (reqUrl.contains("/login/in")){
            return chain.filter(exchange);
        }
        //2 获取请求头jwt token信息

        String jwtToken = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(jwtToken)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3 判断令牌信息是否正确

        try {
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken>0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //解析JWT令牌信息

            Integer id = claims.get("id", Integer.class);
            //日志
            log.info("header token id:{}, URL:{}",id,request.getURI().getPath());
            //4 将令牌信息传递到各个微服务

            ServerHttpRequest serverHttpRequest = request.mutate().headers(
                    httpHeaders -> {
                        httpHeaders.add("userId",String.valueOf(id));
                    }
            ).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5 返回结果

        return chain.filter(exchange);
    }


}
